<!--健康档案队列-->
<template>
  <div class="p-2">
    <el-row >
        <div v-show="showSearch" class="mb-[10px]">
            <el-card shadow="hover">
              <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">

                <el-row>
                  <el-col :span="6">
                   <!--
                    pro:引用的参数
                    v-model:双向绑定,双向绑定的值和prop中的value一致
                    ref:引用的名称
                    -->
                    <el-form-item label="机构名称：" prop="currentManageInstitution">
                      <el-tree-select
                        v-model="form.currentManageInstitution"
                        ref="deptTreeRef"
                        node-key="id"
                        :data="deptOptions"
                        :props="{ value: 'id',label: 'label', children: 'children' }"
                        :filter-node-method="filterNode"
                        highlight-current
                        @node-click="handleNodeClick"
                        check-strictly
                        clearable
                        filterable
                        :filter-method="filterNode"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="6">
                    <el-form-item label="居民姓名：" prop="name">
                      <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable
                                @keyup.enter="handleQuery"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="身份证号：" prop="idCard">
                      <el-input v-model="queryParams.idCard" placeholder="请输入身份证号" clearable
                                @keyup.enter="handleQuery"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="性别：" prop="gender">
                      <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable
                                 @keyup.enter="handleQuery">
                        <el-option v-for="item in sys_user_sex" :key="item.value" :label="item.label"
                                   :value="item.value"/>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <!--<el-col :span="6">-->
                  <!--  <el-form-item label="数据范围：" prop="range">-->
                  <!--    <el-select v-model="queryParams.range" placeholder="请选择" clearable-->
                  <!--               @keyup.enter="handleQuery">-->
                  <!--      <el-option label="本级" :value="true"></el-option>-->
                  <!--      <el-option label="本级及下级" :value="false"></el-option>-->
                  <!--    </el-select>-->
                  <!--  </el-form-item>-->
                  <!--</el-col>-->
                  <el-col :span="6">
                    <el-form-item label="是否签约：" prop="isSign">
                      <el-select v-model="queryParams.isSign" placeholder="请选择" clearable
                                 @keyup.enter="handleQuery">
                        <el-option label="是" :value="true"></el-option>
                        <el-option label="否" :value="false"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6 ">
                    <el-form-item label="签约建档是否一致：" prop="isSignArchive" label-width="150">
                      <el-select v-model="queryParams.isSignArchive" placeholder="请选择" clearable
                                 @keyup.enter="handleQuery">
                        <el-option label="一致" :value="true"></el-option>
                        <el-option label="不一致" :value="false"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item>
                      <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                      <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                  </el-col>

                  <el-col :span="24">
                    <el-form-item label=" 人群标签：" prop="queueInfo">
                      <el-checkbox-group v-model="queryParams.queueInfo" @change="editQueueInfo">
                        <el-checkbox label='高血压' value="hypertension"></el-checkbox>
                        <el-checkbox label='糖尿病' value="diabetes"></el-checkbox>
                        <el-checkbox label='老年人' value="elderly"></el-checkbox>
                        <el-checkbox label='严重精神障碍' value="psychiatric"></el-checkbox>
                        <el-checkbox label='普通人群' value="health_record"></el-checkbox>
                        <el-checkbox label='肺结核' value="tuberculosis"></el-checkbox>
                      </el-checkbox-group>
                    </el-form-item>
                  </el-col>

                </el-row>
              </el-form>
            </el-card>
          </div>

        <el-card shadow="hover">
          <el-table v-loading="loading" :data="patientInfoList" @selection-change="handleSelectionChange">
            <el-table-column label="姓名" align="center" prop="name" width="200"/>
            <el-table-column label="身份证号" align="center" prop="idCard" width="300"/>
            <el-table-column label="人群类型" align="center" prop="queueInfo" width="300">
              <template #default="scope">
                <dict-tag :options="bp_pt_sign" :value="scope.row.queueInfo"/>
              </template>
            </el-table-column>
            <el-table-column label="性别" align="center" prop="gender">
              <template #default="scope">
                <dict-tag :options="sys_user_sex" :value="scope.row.gender"/>
              </template>
            </el-table-column>
            <el-table-column label="年龄" align="center" prop="age" width="100"/>
<!--            <el-table-column label="联系方式" align="center" prop="contactPersonInfo" width="200">-->
<!--              <template #default="scope">-->
<!--                {{ scope.row.contactPersonInfo ? scope.row.contactPersonInfo[0].phone : "" }}-->
<!--              </template>-->
<!--            </el-table-column>-->
            <el-table-column label="个人电话" align="center" prop="personalPhone" width="200"/>

            <el-table-column label="健康档案" align="center" prop="currentManageInstitutionName" width="250"/>
            <el-table-column label="签约" align="center" prop="signOrgName" width="200"/>
            <!--<el-table-column label="最近一次诊疗" align="center" prop="documentationTime" width="320"/>-->

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
              <template #default="scope">
                <el-tooltip content="查看" placement="top">
                  <el-button link type="primary" icon="View" @click="handleLook(scope.row)"
                             v-hasPermi="['basicPublic:patientInfo:edit']"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                      v-model:limit="queryParams.pageSize" @pagination="getList"/>
        </el-card>
<!-- </el-col>-->
    </el-row>

  </div>
</template>


<script setup name="PatientInfo" lang="ts">
import {
  listPatientInfo,
  getPatientInfo,
  delPatientInfo,
  addPatientInfo,
  updatePatientInfo
} from '@/api/basicPublic/patientInfo';
import {
  HealthRecordVO,
  HealthRecordQuery,
  HealthRecordForm
} from '@/api/basicPublic/patientInfo/healthRecord/HealthRecordTypes';
import {getLabelsByValues, parseTime, AddressConcatenation, getCurrentYearsArray} from "../../../utils/ruoyi";
import options from "@/assets/json/address.json";
import {useRouter} from "vue-router";
import {globalHeaders} from '@/utils/request';
import {DeptVO} from "@/api/system/dept/types";
import api, {listUser} from '@/api/system/user';
// import Cascader from "@/components/Cascader/index.vue";

const router = useRouter()
const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {
  bp_pt_sign,
  sys_user_sex,
  bp_complete_status,
  bp_marital_status,
  bp_inspection_type,
  bp_contacts_relationship,
  bp_sign_status,
  bp_inspection_situation
} = toRefs<any>(proxy?.useDict('bp_inspection_situation', 'bp_sign_status', 'bp_contacts_relationship', 'bp_pt_sign', 'sys_user_sex', 'bp_complete_status', 'bp_marital_status', 'bp_inspection_type'));

const patientInfoList = ref<HealthRecordVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(false);//相当与js中的let loading = false;
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);

const total = ref(0);
const deptName = ref('');
const deptOptions = ref<DeptVO[]>([]);//科室下拉框
const uploadRef = ref<ElUploadInstance>();
const queryFormRef = ref<ElFormInstance>();
const patientInfoFormRef = ref<ElFormInstance>();
const documentationDateRange = ref([])
const lastFollowupDateRange = ref([])
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
//
const initFormData: HealthRecordForm = {
  id: undefined,
  name: undefined,
  idCard: undefined,//身份证
  gender: undefined,
  queueId: 'health_record',
  birthday: undefined,
  maritalStatus: undefined,
  personalPhone: undefined,
  residentialAddress: undefined,

  registeredResidence: {
    province: undefined,//户籍地址-省
    provinceCode: undefined,//户籍地址-省代码
    city: undefined,//户籍地址-市
    cityCode: undefined,//户籍地址-市代码
    area: undefined,//户籍地址-区
    areaCode: undefined,//户籍地址-区代码
    street: undefined,//户籍地址-街道
    streetCode: undefined,//户籍地址-街道代码
    committee: undefined,//户籍地址-社区
    committeeCode: undefined,//户籍地址-社区代码
    detail: undefined,//户籍地址-详细地址
  },
  currentResidentialAddress: {
    province: undefined,//户籍地址-省
    provinceCode: undefined,//户籍地址-省代码
    city: undefined,//户籍地址-市
    cityCode: undefined,//户籍地址-市代码
    area: undefined,//户籍地址-区
    areaCode: undefined,//户籍地址-区代码
    street: undefined,//户籍地址-街道
    streetCode: undefined,//户籍地址-街道代码
    committee: undefined,//户籍地址-社区
    committeeCode: undefined,//户籍地址-社区代码
    detail: undefined,//户籍地址-详细地址
  },
  isMaternal: undefined,
  isChildren: undefined,
  contact: undefined,
  contactPhone: undefined,
  documentationTime: undefined,
  documentationPeople: undefined,
  dutyDoctor: undefined,
  archiveNumber: undefined,
  documentationUnit: undefined,
  documentationUnitName: undefined,
  contactPersonInfoRelation: undefined,
  contactPersonInfoName: undefined,
  contactPersonInfoPhone: undefined,
  contactPersonInfo: [
    {
      relation: undefined,
      name: undefined,
      phone: undefined,
    }
  ],
}
const data = reactive<PageData<HealthRecordForm, HealthRecordQuery>>({
  form: {...initFormData},//表单数据initFormData
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    idCard: undefined,
    queueInfo: [],
    personalPhone: undefined,
    birthday: undefined,
    followupStatus: undefined,
    dutyDoctor: undefined,
    documentationUnit: undefined,//档案单位
    documentationUnitName: undefined,
    lastInspectionDate: undefined,
    inspectionType: undefined,
    maritalStatus: undefined,
    gender: undefined,
    archiveNumber: undefined,
    documentationStartDate: undefined,
    documentationEndDate: undefined,
    nextFollowupDate: undefined,
    inspectionSituation: undefined,
    documentationPeople: undefined,
    lastFollowupEndDate: undefined,
    lastFollowupStartDate: undefined,
    isSystemIdentification: undefined,
    isInspection: undefined,//是否已体检
    year: undefined,
    params: {},
    currentManageInstitution:undefined,//现管机构
    // recordInstitution:undefined,//备案机构  需要更改
    range:undefined,//备案范围
    institution: undefined,
    isSignArchive:undefined,
    isSign:undefined,
    state: undefined,
    documentation:undefined,
  },
  rules: {
    // id: [
    //   {required: true, message: "患者id不能为空", trigger: "blur"}
    // ],
    // name: [
    //   {required: true, message: "姓名不能为空", trigger: "blur"}
    // ],
    // idCard: [
    //   {required: true, message: "身份证号不能为空", trigger: "blur"},
    //   {min: 18, max: 18, message: "请输入正确的身份证号", trigger: "blur"}
    // ],
    // gender: [
    //   {required: true, message: "性别不能为空", trigger: "change"}
    // ],
    // birthday: [
    //   {required: true, message: "出生日期不能为空", trigger: "blur"}
    // ],
    // archiveNumber: [
    //   {required: true, message: "档案号不能为空", trigger: "blur"}
    // ],
    // personalPhone: [
    //   {required: true, message: "个人电话不能为空", trigger: "blur"},
    //   {min: 11, max: 11, message: "请输入正确的电话号", trigger: "blur"}
    // ],
    // contactPhone: [
    //   {min: 11, max: 11, message: "请输入正确的手机号", trigger: "blur"}
    // ],
    // currentResidentialAddress: [
    //   {required: true, message: "居住地址不能为空", trigger: "blur"}
    // ],
    // contactPersonInfoPhone: [
    //   {required: true, message: "联系人电话不能为空", trigger: "blur"}
    // ],
    // contactPersonInfoRelation: [
    //   {required: true, message: "联系人关系和电话不能为空", trigger: "blur"}
    // ],
    // contactPersonInfoName: [
    //   {required: true, message: "联系人姓名不能为空", trigger: "blur"}
    // ],
  }
});

/*** 用户导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/basicPublic/patientInfo/importData'
});


const {queryParams, form, rules} = toRefs(data);


const handleSelectedAdress = (value) => {
  form.value.currentResidentialAddress = value
};

// 编辑联系人信息,多项选项框
const editQueueInfo = (value) => {
  console.log('editQueueInfo',value)//打印当先选中的数据
  // if (value.length > 1) {
  //   if (value.indexOf(form.value.queueId) > -1) {
  //     queryParams.value.queueInfo = value.filter(it => it != form.value.queueId)
  //   }
  // } else if (value.length == 1 && value.indexOf(form.value.queueId) == -1){
  //   queryParams.value.queueInfo = value
  // }else {
  //   queryParams.value.queueInfo = [form.value.queueId]
  // }
}


const handleSelectedResidence = (value) => {
  form.value.registeredResidence = value
};


/** 获取医生字典  暂时没用 */
const doctorDictList = ref<any[]>([]);
const doctorDictLists = ref<any[]>([]);

const getDoctorDictList = async () => {
  const res = await listUser();
  console.log('获取医生字典',res)
  doctorDictList.value = res.rows
  doctorDictLists.value = doctorDictList.value.map(it => ({
    elTagClass: "",
    elTagType: "",
    label: it.nickName,
    value: String(it.userId),
  }))
}


/** 查询患者基本信息列表 */
const getList = async () => {
  loading.value = true;//是否打开加载
  // setDateRange(documentationDateRange.value, 'documentationStartDate', 'documentationEndDate', 'params');
  // if ((queryParams.value.isInspection || queryParams.value.isSystemIdentification) && !queryParams.value.year) {
  //   proxy?.$modal.msgWarning("是否健康体检、是否中医体质辨识必须关联年份查询，请选择年份！");
  //   loading.value = false;
  //   return;
  // }
  // if (!queryParams.value.currentManageInstitution) {
  //   proxy?.$modal.msgWarning("请选择现管机构");
  //   loading.value = false;
  //   return;
  // }
  // console.log('查询之前的参数',queryParams.value)
  const res = await listPatientInfo(queryParams.value);//调用接口,参数都是queryParams.value
  console.log('查询患者基本信息列表',res)
  // patientInfoList.value = res.rows as HealthRecordVO[];
  patientInfoList.value = res.rows as HealthRecordVO[];
  total.value = res.total;//分页
  // console.log('查询患者基本信息列表',patientInfoList.value)
  loading.value = false;
}


const setDateRange = (dateRange, startDateKey, endDateKey, pin) => {
  if (dateRange) {
    queryParams.value[pin][startDateKey] = parseTime(dateRange[0]);
    queryParams.value[pin][endDateKey] = parseTime(dateRange[1]);
  } else {
    queryParams.value[pin][startDateKey] = undefined;
    queryParams.value[pin][endDateKey] = undefined;
  }
};


/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  queryParams.value.idCard = undefined
}


/** 查询部门下拉树结构 */
const getTreeSelect = async () => {
  const res = await api.deptTreeSelect();
  deptOptions.value = res.data;
};


/**现管机构节点单击事件 */
const handleNodeClick = (data: DeptVO) => {
  queryParams.value.currentManageInstitution = data.id;
};
/**档案机构节点单机事件 */
const recordClick = (data: DeptVO) => {
  queryParams.value.documentationUnit = data.id;
}



/** 通过条件过滤节点  */
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};


/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  patientInfoFormRef.value?.resetFields();
}


/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  lastFollowupDateRange.value = undefined
  documentationDateRange.value = undefined

  handleQuery();
}

/** 重置按钮操作 */
const resetQuerys = () => {
  reset()
  queryParams.value.idCard = undefined
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: HealthRecordVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加健康档案基本信息";
}


/** 查看按钮操作 */

const handleLook = (row?: HealthRecordVO) => {
  // console.log($router)
  router.push({
    path: '/workBenches/workBenches',
    query: {
      id: row?.id
    }
  })
}


/** 提交按钮 */
const submitForm = () => {
  patientInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.contactPersonInfo = [
        {
          relation: undefined,
          name: undefined,
          phone: undefined,
        }
      ]
      form.value.contactPersonInfo[0].relation = form.value.contactPersonInfoRelation
      form.value.contactPersonInfo[0].name = form.value.contactPersonInfoName
      form.value.contactPersonInfo[0].phone = form.value.contactPersonInfoPhone
      await addPatientInfo(form.value).finally(() => buttonLoading.value = false);
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
    }
  });
}


/** 删除按钮操作 */
const handleDelete = async (row?: HealthRecordVO) => {
  const _ids = row?.id || ids.value;
  const _name = row?.name
  await proxy?.$modal.confirm('是否确认删除患者"' + _name + '"的基本信息？').finally(() => loading.value = false);
  await delPatientInfo(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('basicPublic/patientInfo/export', {
    ...queryParams.value
  }, `patientInfo_${new Date().getTime()}.xlsx`)
}

/** 打开导入表弹窗 */
/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '患者信息导入';
  upload.open = true;
};
/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
/** 下载模板操作 */
const importTemplate = () => {
  proxy?.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`);
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {

  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);

  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  });
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}


const handleChange = (value) => {
  console.log(getLabelsByValues(value, options))
}


onMounted(() => {
  getTreeSelect();
  getDoctorDictList();
  // getList();
});

</script>
<style scoped lang="scss">
::v-deep .el-cascader {
  .el-input {
    //width: 300px;
  }
}
</style>
